<template>
  <div v-loading="loading">
    <MciTable :data="tableData" stripe>
      <MciTableColumn type="index" label="序号" align="center" :index="indexMethod" width="50" />
      <MciTableColumn label="开始执行时间" prop="startTime" :formatter="formatterStart" />
      <MciTableColumn label="执行结果" prop="status">
        <template #default="scope">
          <mci-button :type="scope.row.status === 1 ? 'success' : 'danger'" link>
            {{ scope.row.status === 1 ? '成功' : '失败' }}
          </mci-button>
        </template>
      </MciTableColumn>
      <MciTableColumn label="结束时间" prop="endTime" :formatter="formatterEnd" />
      <MciTableColumn label="批次号" min-width="160">
        <template #default="scope">
          <ElPopover placement="left" :width="240" trigger="hover">
            <template #reference>
              <mci-button type="primary" link> {{ scope.row.execId }} </mci-button>
            </template>
            <div class="flex flex-col">
              <h4 style="text-align: left">决策</h4>
              <div v-for="item in props.flowIds" :key="item" class="py-4">
                <mci-button type="primary" link @click="handleDetail(scope.row, item)"> {{ item }} </mci-button>
              </div>
            </div>
          </ElPopover>
        </template>
      </MciTableColumn>
    </MciTable>
    <MciPagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 15, 20, 30, 50]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <ElDialog
      destroy-on-close
      append-to-body
      fullscreen
      class="flow-detail-dialog"
      :title="currFlowName"
      :model-value="!!currFlowId"
      @close="
        () => {
          currFlowName=''
          currFlowId=''
          flowDetail = {};
        }
      "
    >
      <GraphContainer flow-state="view" class="w-full h-screen" :graph-json="json" />
    </ElDialog>
  </div>
</template>

<script lang="ts" setup>
import { PropType, ref } from 'vue';
import { MciTable, MciTableColumn, MciButton, MciPagination } from '@/components/base';
import { GraphContainer } from '@/components/business/GraphContainer';
import { ElDialog } from 'element-plus';
import { getDecisionFlowGet, postJobLogPage, getFlowResultExecDetails } from '@/api/decision-engine';
import type { IPostFlowResultPageRes, IPostJobLogPageReq, IPostJobLogPageRes } from '@/api/decision-engine';
import { useDateFormat } from '@vueuse/core';
import { useGraph } from '@/hooks/useGraph';
import { useNodeResults } from '@/store/node-results';
import { showNodeStatusWithState } from '@/utils/graph';

const props = defineProps({
  // 流程标识
  flowIds: {
    type: Array as PropType<string[]>,
    default: () => []
  },
  // 任务标识
  jobId: {
    type: String,
    default: ''
  }
});
// const emit = defineEmits<{
//   (e: 'edit', dataModal: any): void;
// }>();
// 表格
const loading = ref(false);
const tableData = ref<any[]>([]);
// 翻页
const currentPage = ref(1);
const pageSize = ref(15);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const pageTotal = ref(0);
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  tableRequest();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  tableRequest();
};
// 序号列index
const indexMethod = (index: number) => {
  return pageSize.value * (currentPage.value - 1) + index + 1;
};

const formatterStart = (row: any) => {
  return row.startTime ? useDateFormat(new Date(row.startTime), 'YYYY/MM/DD HH:mm').value : '--';
};
const formatterEnd = (row: any) => {
  return row.endTime ? useDateFormat(new Date(row.endTime), 'YYYY/MM/DD HH:mm').value : '--';
};

// 详情
type TFlowDetail = Required<IPostFlowResultPageRes>['list'][0];
const flowDetail = ref({} as TFlowDetail);
const json = ref({});
const router = useRouter();
const execResult = useNodeResults();
const { graph, updateInteractingState } = useGraph();

// 模型数据
const tableRequest = async () => {
  loading.value = true;
  const params: IPostJobLogPageReq = {
    jobId: props.jobId,
    pageNo: currentPage.value,
    pageSize: pageSize.value
  };
  try {
    const data: IPostJobLogPageRes = await postJobLogPage(params);

    if (data && data.currentPage === currentPage.value) {
      tableData.value = data.list || [];
      pageTotal.value = data.total || 0;
    }
  } finally {
    setTimeout(() => {
      loading.value = false;
    }, 300);
  }
};

tableRequest();

// 批次号详情
const currFlowId = ref('');
const currFlowName = ref('');
const handleDetail = async (row: any, flowId: string) => {
  if (!row || !row.execId || !flowId) return;
  flowDetail.value = row;
  currFlowId.value = flowId;
  execResult.clearResults();

  updateInteractingState(false);

  router.replace({
    query: {
      flowId
    }
  });

  const res = await getDecisionFlowGet({ flowId });
  if(res)currFlowName.value = res.flowName;
  try {
    json.value = JSON.parse(res.graph!);
  } catch (err) {}

  getFlowResultExecDetails({ execId: row.execId!, flowId }).then((res) => {
    execResult.resultsOfList.push(...(res.lineResults || []));
    execResult.resultsOfList.push(...(res.nodeResults || []));

    execResult.resultsOfList.map((item) => {
      showNodeStatusWithState(graph.value!, item, false);
    });
  });
};

defineExpose({
  tableRequest
});
</script>
